package com.lmx.persistence.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;
import com.lmx.common.constants.CommonConstants;
import com.lmx.persistence.service.common.BaseCrudServiceImpl;
import com.lmx.repoDomain.tmodel.Tenant;
import com.lmx.repoDomain.tmodel.TenantPrivilege;

@Service
public class TenantPrivilegeServiceImpl extends
		BaseCrudServiceImpl<TenantPrivilege> implements TenantPrivilegeService {

	@Override
	public void allocateSysPrivilege(Tenant tenant, Integer sysType) {
		this.deleteByTenantId(tenant.getId());
		String insertSql = "insert into tnb_tenant_privilege(privilege_id,tenant_id) (select id,?1 from t_s_function as fun where del_status=0 && (fun.functiontype=1 || fun.functiontype=3) && fun.system_type=?2 )";
		super.em.createNativeQuery(insertSql).setParameter(1, tenant.getId())
				.setParameter(2, sysType).executeUpdate();
		List<TenantPrivilege> privileges = super.find("tenant", tenant);
		tenant.setPrivileges(privileges);
	}

	@Override
	public void deleteByTenantId(Long tenantId) {
		String deleteSql = "DELETE FROM tnb_tenant_privilege WHERE tenant_id = :id ";
		super.em.createNativeQuery(deleteSql).setParameter("id", tenantId)
				.executeUpdate();
	}

	@Override
	@Transactional(readOnly = true)
	public void addPrivileges(Tenant tenant) {
		if (tenant == null) {
			return;
		}
		Tenant tenant2 = new Tenant();
		BeanUtils.copyProperties(tenant, tenant2);
		Map<String, Object> param = Maps.newHashMap();
		param.put("tenant.id", tenant.getId());
		param.put("delStatus", CommonConstants.DEL_STATUS_NO_0);
		List<TenantPrivilege> privileges = super.find(param);
		for (TenantPrivilege tenantPrivilege : privileges) {
			tenantPrivilege.setTenant(tenant2);
			if (tenantPrivilege.getPrivilege() != null) {
				tenantPrivilege.getPrivilege().setTenant(tenant2);
				tenantPrivilege.getPrivilege().setChildren(null);
			}
		}
		tenant.setPrivileges(privileges);
	}

	/**
	 *   查询所有租户权限数据
	 *   @author huibati
	 *   @param
	 *   2017年11月28日
	 */
	@Override
	public Iterable<Tenant> addAllTenantPrivileges(Iterable<Tenant> tenants) {
		if (tenants == null) {
			return tenants;
		}
		int size = 0;
		Iterator iter = tenants.iterator();
		//获取全部租户权限数据
		List<Tenant> tenantList= new ArrayList<>();
		List privilegesTemp = new ArrayList<>();
		privilegesTemp = super.em.createQuery(" select tp,t from TenantPrivilege tp,Tenant t where tp.tenant in (:tenants) and tp.delStatus !=1 and tp.tenant.id=t.id")
		.setParameter("tenants", tenants).getResultList();
		//根据租户id建立权限map
		Map<Long,List<TenantPrivilege>> priMap = new HashMap<>();
		iter = privilegesTemp.iterator();
		while (iter.hasNext()) {
			Object[] res = (Object[]) iter.next();
			TenantPrivilege tp = new TenantPrivilege();
			Tenant t = new Tenant();
			tp = ((TenantPrivilege) res[0]);
			t = ((Tenant) res[1]);
			tp.setTenant(t);
			if (tp.getPrivilege() != null) {
				tp.getPrivilege().setTenant(t);
				tp.getPrivilege().setChildren(null);
			}
			if(priMap.containsKey(t.getId())){
				priMap.get(t.getId()).add(tp);
			}else{
				List<TenantPrivilege> tps= new ArrayList<>();
				tps.add(tp);
				priMap.put(t.getId(),tps);
			}

		}
		iter = tenants.iterator();
		while (iter.hasNext()) {
			Tenant tenant=(Tenant) iter.next();
			if(priMap.containsKey(tenant.getId())){
				tenant.setPrivileges(priMap.get(tenant.getId()));
			}
			tenantList.add(tenant);
		}
		
		return tenantList;
	}
	
	@Override
	public List<TenantPrivilege> findInitTenantPrivilkeges(Long tenantId) {
		String queryStr = "from TenantPrivilege as tp where tp.tenant.id = :tenantId"
				+ " and ( tp.privilege.type=0 or tp.privilege.type=1 or tp.privilege.type=3)"
				+ " and delStatus=0";
		return super.em.createQuery(queryStr)
				.setParameter("tenantId", tenantId).getResultList();
	}
}
